package com.financing.platform.task;

import java.io.FileInputStream;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.platform.dao.IFaUserDao;
import com.financing.platform.dao.ISwitchDao;
import com.financing.platform.dto.FaAutoRegisterToManagerDTO;
import com.financing.platform.dto.FaUserDTO;
import com.financing.platform.dto.SwitchDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IFaAutoRegisterToManagerService;
import com.financing.platform.service.IFaUserService;
import com.financing.platform.service.IManagerLicaishiService;
import com.financing.platform.util.AliyunMobileQueryUtil;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.HtmlUnitFetchUtil;
import com.financing.platform.util.MemcacheCacheHelper;
import com.financing.platform.util.MessageUtil;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.ManagerLicaishiVO;

@Component("autoRegisterToManagerJob")
public class AutoRegisterToManagerJob {
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private IFaUserService faUserService;
	
	@Autowired
	IManagerLicaishiService managerLicaishiServiceImpl;
	
	@Autowired
	private IFaUserDao faUserDaoImpl;
	
	@Autowired
	private ISwitchDao switchDaoImpl;
	
	@Autowired
	private MailSenderService mailSenderService;
	
	@Autowired
	private IFaAutoRegisterToManagerService faAutoRegisterToManagerService;
	
	final String chengduProv="广东 ,广西 ,海南 ,湖南 ,福建 ,云南 ,四川 ,宁夏 ,新疆 ,湖北 ,甘肃 ,西藏 ,贵州 ,重庆 ,陕西 ,青海";
	final String shanghaiProv="内蒙古 ,北京 ,吉林 ,天津 ,山东 ,山西 ,河北 ,河南 ,辽宁 ,黑龙江 ,上海 ,安徽 ,江苏 ,江西 ,浙江";
	//测试环境  成都 分配给技术部    上海  分配给 运营部
//	final String chengduProv_suid="707f4f2d-bdb3-11e6-ba00-d89d672b90bc";
//	final String shanghaiProv_suid="9d3d7241-bf75-11e7-b8ea-ecf4bbce3884";
	final String currentInfo = "system";
	
	@Value("#{settings['chengduProv_suid']}")
	private String chengduProv_suid;
	
	@Value("#{settings['shanghaiProv_suid']}")
	private String shanghaiProv_suid;
	
	final String fmt = "yyyy-MM-dd";
	
	/***
	 * 自动分配注册的人
	 */
	@Scheduled(cron = "0 0/30 * * * ?") 
	public void autoRegisterToManager(){
		Date addDay = DateUtil.addDay(new Date(), -1);
		
		//查询出最近两天注册没有被分配过的人
		try {
			//不能自动删除
			Object autoRegisterToManager=MemcacheCacheHelper.mcc.get("autoRegisterToManager");
			if(autoRegisterToManager!=null){
				Date d=(Date)autoRegisterToManager;
				if(d.before(new Date())){
					MemcacheCacheHelper.mcc.delete("autoRegisterToManager");
				}
			}
			
			//获取memcache
			Date date = new Date(System.currentTimeMillis()+10*60*1000);
			if(!MemcacheCacheHelper.mcc.add("autoRegisterToManager",date,date)){
				logger.info("autoRegisterToManager running");
				return;
			}
			//开关 
			SwitchDTO switchs = new SwitchDTO();
			switchs.setsKey("autoRegisterToManager");
			switchs = switchDaoImpl.querySwitch(switchs);
			if(null != switchs && Dict.switchOn.equals(switchs.getsValue())){
				List<FaUserDTO> queryFaUserNomanager = faUserService.queryFaUserNomanager(DateUtil.formatDate(addDay, "yyyy-MM-dd"));
				
				StringBuffer chengdu = new StringBuffer();
				
				StringBuffer shanghai = new StringBuffer();
				
				for (FaUserDTO faUserDTO : queryFaUserNomanager) {
					//修改用户的所在省份城市信息
					try {
						String loginName = faUserDTO.getuLoginName();
						if(StringUtil.isNullOrEmptyStr(loginName)||!loginName.matches("\\d{11}")){
							continue;
						}
						JSONObject mobileQuery = AliyunMobileQueryUtil.mobileQuery(loginName);
						String ret = mobileQuery.getString("ret");
						//请求成功json = {"ret":200,"msg":"success【为了提供更好的服务与支持，接口返回数据格式将统一去除result一层（具体参考阿里云接口详情页最新格式），请调用方尽快按要求修改，以免造成不必要损失，详情咨询详情页在线客服】","data":{"result":{"result":null,"types":"中国移动 GSM","lng":"121.473701","city":"上海","num":1500077,"isp":"移动","area_code":"310100","city_code":"021","prov":"上海","zip_code":"200000","lat":"31.230416"},"types":"中国移动 GSM","lng":"121.473701","city":"上海","num":1500077,"isp":"移动","area_code":"310100","city_code":"021","prov":"上海","zip_code":"200000","lat":"31.230416"},"log_id":"25980B6E-0F72-445C-84A2-FDDB01B26B7F"}
						if("200".equals(ret)){
							//保存   英文格式可能修改  直接正则匹配
							String prov = HtmlUnitFetchUtil.fecth(mobileQuery.toString(), "\"prov\"\\:\"(.*?)\"", 1);
							if(chengduProv.contains(prov)){
								chengdu.append(",").append(faUserDTO.getId());
							}else if(shanghaiProv.contains(prov)){
								shanghai.append(",").append(faUserDTO.getId());
							}
							faUserDTO.setuMobileAdd(prov);
							faUserDTO.setUpdateBy("autoRegisterToManager");
							faUserDaoImpl.updateFaUserInfo(faUserDTO);
						}
					} catch (Exception e) {
						logger.info("autoRegisterToManager updateFaUserInfo error",e);
					}
				}
				
				UserInfoDTO user=new UserInfoDTO();
				user.setUsername(currentInfo);
				ManagerLicaishiVO managerLicaishiVo=new ManagerLicaishiVO();
				managerLicaishiVo.setCreateBy(currentInfo);
				managerLicaishiVo.setUpdateBy(currentInfo);
				managerLicaishiVo.setCreateDate(new Date());
				managerLicaishiVo.setUpdateDate(new Date());
				//自动分配 成都
				if(!StringUtil.isNullOrEmptyNStr(chengdu.toString())){
					managerLicaishiVo.setSystemUserId(chengduProv_suid);
					managerLicaishiVo.setLicaishiIds(chengdu.substring(1));
					int count = managerLicaishiServiceImpl.batchAddManagerLicaishiUser(managerLicaishiVo,user);
					logger.info("autoRegisterToManager batchAddManagerLicaishiUser chengducount:"+count);
					
					//记录分配日志
					String[] split = chengdu.substring(1).split(",");
					for (int i = 0; i < split.length; i++) {
						if(StringUtil.isNullOrEmptyNStr(split[i]))continue;
						FaAutoRegisterToManagerDTO faAutoRegisterToManager=new FaAutoRegisterToManagerDTO();
						faAutoRegisterToManager.setAutoAssignedIds(split[i]);
						//成都
						faAutoRegisterToManager.setAutoAssignedType("2");
						log(faAutoRegisterToManager);
					}
				}
				
				//自动分配  上海
				if(!StringUtil.isNullOrEmptyNStr(shanghai.toString())){
					managerLicaishiVo.setSystemUserId(shanghaiProv_suid);
					managerLicaishiVo.setLicaishiIds(shanghai.substring(1));
					int count = managerLicaishiServiceImpl.batchAddManagerLicaishiUser(managerLicaishiVo,user);
					logger.info("autoRegisterToManager batchAddManagerLicaishiUser shanghaicount:"+count);
					
					//记录分配日志
					String[] split=shanghai.substring(1).split(",");
					for (int i = 0; i < split.length; i++) {
						if(StringUtil.isNullOrEmptyNStr(split[i]))continue;
						FaAutoRegisterToManagerDTO faAutoRegisterToManager=new FaAutoRegisterToManagerDTO();
						faAutoRegisterToManager.setAutoAssignedIds(split[i]);
						//成都
						faAutoRegisterToManager.setAutoAssignedType("1");
						log(faAutoRegisterToManager);
					}
					
				}
				
			}else{
				logger.info("autoRegisterToManager is off");
			}
		} catch (SQLException e) {
			//
			logger.error("autoRegisterToManager error:",e);
		}finally{
			MemcacheCacheHelper.mcc.delete("autoRegisterToManager");
		}
		
	}

//分配日志
	private void log(FaAutoRegisterToManagerDTO faAutoRegisterToManager)
			throws SQLException {
		faAutoRegisterToManager.setCreateBy(currentInfo);
		faAutoRegisterToManager.setUpdateBy(currentInfo);
		faAutoRegisterToManager.setCreateDate(new Date());
		faAutoRegisterToManager.setUpdateDate(new Date());
		faAutoRegisterToManager.setDeleteTag("1");
		faAutoRegisterToManagerService.insert(faAutoRegisterToManager);
	}
	
	
	/***
	 * 自动发送注册人数邮件
	 */
	@Scheduled(cron = "0 0 18 * * ?") 
	public void autoSendRegAuthEmail(){
		//自动发送注册人数邮件
		try {
			logger.info("begin autoSendRegAuthEmail ");
			
//			不能自动删除
			Object autoSendRegAuthEmail=MemcacheCacheHelper.mcc.get("autoSendRegAuthEmail");
			if(autoSendRegAuthEmail!=null){
				Date d=(Date)autoSendRegAuthEmail;
				if(d.after(new Date())){
					logger.info("begin autoSendRegAuthEmail not out time delete ");
//					MemcacheCacheHelper.mcc.delete("autoSendRegAuthEmail");
					return ;
				}
			}
			
			//获取memcache
			Date date = new Date(System.currentTimeMillis()+10*60*1000);
			if(!MemcacheCacheHelper.mcc.add("autoSendRegAuthEmail",date,date)){
				logger.info("autoSendRegAuthEmail is running");
				return;
			}
			logger.info("begin autoSendRegAuthEmail run");
			//开关 
			SwitchDTO switchs = new SwitchDTO();
			switchs.setsKey("autoSendRegAuthEmail");
			switchs = switchDaoImpl.querySwitch(switchs);
			if(null != switchs && Dict.switchOn.equals(switchs.getsValue())){
				Date d=new Date();
//				//测试环境是否取文件内容地址
//				java.io.File f=new java.io.File("/disk/upload/testDate.txt");
//				String str = IOUtils.toString(new FileInputStream(f));
//				d=DateUtil.format(str, fmt);
				
				int month = d.getMonth();
				//判断今天是否月底
				Date addDay = DateUtil.addDay(d,1);
				int nextDayMonth=addDay.getMonth();
				
				String startDate = "";
				//判断今天是否周五
				int day=DateUtil.dayForWeek(DateUtil.formatDate(d,fmt));
				
				if(month==nextDayMonth){//非月底 
					if(day!=5){
						//既非周五
						logger.info("no where running ");
						return;
					}
					//上周五是否上个月
					Date lastFriday=DateUtil.getDayOfWeek(Calendar.FRIDAY, -1);
					int lastFridaymonth = lastFriday.getMonth();
					if(lastFridaymonth==month){
						//上周五为当月  则取上周五的数据
						startDate=DateUtil.formatDate(lastFriday,fmt)+" 18:00:00";
					}else{
						//上周五为上个月  则取上个月最后一天
						startDate=DateUtil.getLastAndDay()+" 18:00:00";
					}
				}else {
					//月底 需要发送
					Date lastFriday=DateUtil.getDayOfWeek(Calendar.FRIDAY, -1);
					startDate=DateUtil.formatDate(lastFriday,"YYYY-MM-dd")+" 18:00:00";
				}
				
				//结束日期为今天的日期  
				String endDate=DateUtil.formatDate(d,fmt)+" 18:00:00";
				
				//查询当前18点钟到前一日18点钟
				FaAutoRegisterToManagerDTO faAutoRegisterToManager=new FaAutoRegisterToManagerDTO();
				
				faAutoRegisterToManager.setStartDate(startDate);
				faAutoRegisterToManager.setEndDate(endDate);
				Map<String, Object> quqeryAutoUser = faAutoRegisterToManagerService.quqeryAutoUser(faAutoRegisterToManager);
				
				//查询本月总分配人数  上海
				Map<String, String> queryCurrentMonthUser = faAutoRegisterToManagerService.queryCurrentMonthUser(faAutoRegisterToManager);
				//昨天到今天成都注册的人数   上海
				String currentMonthUsersh = queryCurrentMonthUser.get("1");
				//成都
				String currentMonthUsercd = queryCurrentMonthUser.get("2");
				quqeryAutoUser.put("currentMonthUsersh", currentMonthUsersh==null?"0":currentMonthUsersh);
				quqeryAutoUser.put("currentMonthUsercd", currentMonthUsercd==null?"0":currentMonthUsercd);
				
				//发送邮件
				Map<String,Object> mailMap = MessageUtil.getMsgInfo("noticeAuditMailTemplate", "sendRegAuthEmail", quqeryAutoUser);
				//发送邮件
				MailContentDTO mail = new MailContentDTO();
				mail.setContext((String)mailMap.get(MessageUtil.KEY_CONTENT));
				mail.setRecAddress(((String)mailMap.get("mailto")));
				mail.setCc((String)mailMap.get("cc"));
				String titile="平台注册资源记录已更新 "+DateUtil.getDate(fmt);
				mail.setSubject(titile);
				mail.setRequestTime(new Date());
				mailSenderService.send(mail);
			}else{
				logger.info("autoSendRegAuthEmail is off");
			}
		} catch (Exception e) {
			//
			logger.error("autoSendRegAuthEmail error:",e);
		}finally{
			MemcacheCacheHelper.mcc.delete("autoSendRegAuthEmail");
		}
		
		
	}
	public static void main(String[] args) {
		System.out.println(new String(Base64.decodeBase64("MTMzMzI4MzA0MTM".getBytes())));
	}
}
